<template>
  <view class="container">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">好友申请</text>
    </view>

    <!-- 申请状态筛选 -->
    <view class="filter-tabs">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index" 
        :class="['tab-item', currentTab === index ? 'active' : '']"
        @tap="switchTab(index)"
      >
        <text class="tab-text">{{ tab.name }}</text>
        <text v-if="tab.count > 0" class="tab-count">{{ tab.count > 99 ? '99+' : tab.count }}</text>
      </view>
    </view>

    <!-- 空状态提示 -->
    <view v-if="filteredRequests.length === 0" class="empty-state">
      <image src="/static/images/empty-notification.png" mode="widthFix" class="empty-img"></image>
      <text class="empty-text">暂无{{ tabs[currentTab].name }}的好友申请</text>
    </view>

    <!-- 申请列表 -->
    <view v-else class="requests-list">
      <view 
        class="request-item" 
        v-for="(request, index) in filteredRequests" 
        :key="index"
      >
        <image 
          :src="request.avatarUrl || '/static/images/default-avatar.png'" 
          mode="aspectFill" 
          class="user-avatar"
        ></image>
        
        <view class="request-info">
          <view class="user-info">
            <text class="user-name">{{ request.nickName || '未知用户' }}</text>
            <text class="request-time">{{ formatTime(request.applyTime) }}</text>
          </view>
          
          <text class="request-message">
            请求添加您为好友
          </text>
          
          <!-- 状态标签 -->
          <view class="status-tag" :class="getStatusClass(request.friendStatus)">
            {{ getStatusText(request.friendStatus) }}
          </view>
        </view>
        
        <!-- 操作按钮 (仅待处理状态显示) -->
        <view v-if="request.friendStatus === 0" class="action-buttons">
          <button class="action-btn accept-btn" @tap="acceptRequest(request)">同意</button>
          <button class="action-btn reject-btn" @tap="rejectRequest(request)">拒绝</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import userManager from '@/common/utils/user.js'
import { getAllFriendRequests, agreeFriend, refuseFriend } from '@/api/friend.js'
import messageCenter from '@/common/utils/messagecenter.js'
import TimeUtil from '@/common/utils/time.js'

export default {
  setup() {
    const currentTab = ref(0)
    const friendRequests = ref([])
    const loading = ref(false)
    
    // 筛选标签
    const tabs = computed(() => {
      const allRequests = friendRequests.value
      return [
        { 
          name: '全部', 
          count: allRequests.length 
        },
        { 
          name: '待处理', 
          count: allRequests.filter(req => req.friendStatus === 0).length 
        },
        { 
          name: '已同意', 
          count: allRequests.filter(req => req.friendStatus === 1).length 
        },
        { 
          name: '已拒绝', 
          count: allRequests.filter(req => req.friendStatus === 2 || req.friendStatus === 4).length 
        }
      ]
    })
    
    // 根据当前标签筛选申请
    const filteredRequests = computed(() => {
      const requests = friendRequests.value
      switch(currentTab.value) {
        case 1: // 待处理
          return requests.filter(req => req.friendStatus === 0)
        case 2: // 已同意
          return requests.filter(req => req.friendStatus === 1)
        case 3: // 已拒绝
          return requests.filter(req => req.friendStatus === 2 || req.friendStatus === 4)
        default: // 全部
          return requests
      }
    })
    
    // 切换标签
    const switchTab = (index) => {
      currentTab.value = index
    }
    
    // 格式化时间
    const formatTime = (time) => {
      if (!time) return ''
      const date = new Date(time)
      // 检查日期是否有效
      if (isNaN(date.getTime())) return ''
      
      const now = new Date()
      const diff = now - date
      
      // 如果是今天，显示时:分
      if (date.toDateString() === now.toDateString()) {
        return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
      }
      
      // 如果是昨天，显示昨天
      const yesterday = new Date(now)
      yesterday.setDate(yesterday.getDate() - 1)
      if (date.toDateString() === yesterday.toDateString()) {
        return '昨天'
      }
      
      // 如果是一周内，显示星期几
      if (diff < 7 * 24 * 60 * 60 * 1000) {
        const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
        return weekdays[date.getDay()]
      }
      
      // 其他情况显示月/日
      return `${date.getMonth() + 1}/${date.getDate()}`
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        0: '待处理',
        1: '已同意',
        2: '已拒绝',
        4: '已拒绝'
      }
      return statusMap[status] || '未知'
    }
    
    // 获取状态样式类
    const getStatusClass = (status) => {
      const classMap = {
        0: 'pending',
        1: 'accepted',
        2: 'rejected',
        4: 'rejected'
      }
      return classMap[status] || ''
    }
    
    // 获取好友申请列表
    const fetchFriendRequests = async () => {
      if (loading.value) return
      
      const currentUser = userManager.getUserInfo()
      if (!currentUser || !currentUser.userId) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      
      loading.value = true
      try {
        const res = await getAllFriendRequests(currentUser.userId)
        if (res.data.code === 200) {
          friendRequests.value = res.data.data || []
        } else {
          uni.showToast({
            title: res.data.message || '获取好友申请失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取好友申请失败:', error)
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        })
      } finally {
        loading.value = false
      }
    }
    
    // 同意好友申请
    const acceptRequest = async (request) => {
      const currentUser = userManager.getUserInfo()
      if (!currentUser || !currentUser.userId) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      
      uni.showModal({
        title: '确认同意',
        content: `确定要同意${request.nickName}的好友申请吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const result = await agreeFriend(currentUser.userId, request.userId)
              if (result.data.code === 200) {
                uni.showToast({
                  title: '已同意好友申请',
                  icon: 'success'
                })
                
                // 更新本地状态
                request.friendStatus = 1
                request.agreeTime = new Date()
                
                // 重新加载数据以确保状态同步
                fetchFriendRequests()
              } else {
                uni.showToast({
                  title: result.data.message || '操作失败',
                  icon: 'none'
                })
              }
            } catch (error) {
              console.error('同意好友申请失败:', error)
              uni.showToast({
                title: '操作失败',
                icon: 'none'
              })
            }
          }
        }
      })
    }
    
    // 拒绝好友申请
    const rejectRequest = async (request) => {
      const currentUser = userManager.getUserInfo()
      if (!currentUser || !currentUser.userId) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      
      uni.showModal({
        title: '确认拒绝',
        content: `确定要拒绝${request.nickName}的好友申请吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const result = await refuseFriend(currentUser.userId, request.userId)
              if (result.data.code === 200) {
                uni.showToast({
                  title: '已拒绝好友申请',
                  icon: 'success'
                })
                
                // 更新本地状态
                request.friendStatus = 2
                
                // 重新加载数据以确保状态同步
                fetchFriendRequests()
              } else {
                uni.showToast({
                  title: result.data.message || '操作失败',
                  icon: 'none'
                })
              }
            } catch (error) {
              console.error('拒绝好友申请失败:', error)
              uni.showToast({
                title: '操作失败',
                icon: 'none'
              })
            }
          }
        }
      })
    }
    
    onMounted(() => {
      fetchFriendRequests()
      
      // 清除所有好友申请相关的未读消息
      const notificationChats = messageCenter.chatList.filter(c => 
        c.chatType === 'notification' && 
        c.user &&
        (c.user.action === 'friend_request' || 
         c.user.action === 'friend_accepted' || 
         c.user.action === 'friend_rejected')
      )
      
      notificationChats.forEach(chat => {
        // 标记所有消息为已读
        chat.readNum = chat.list.length
        chat.readTime = TimeUtil.now ? TimeUtil.now() : new Date().toLocaleString()
        messageCenter.setReadTime(chat)
      })
      
      // 更新TabBar徽章
      setTimeout(() => {
        messageCenter.calculateUnreadCounts(true)
      }, 100)
    })
    
    return {
      currentTab,
      tabs,
      filteredRequests,
      switchTab,
      formatTime,
      getStatusText,
      getStatusClass,
      acceptRequest,
      rejectRequest
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  background-color: #fff;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.filter-tabs {
  display: flex;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
  position: relative;
}

.tab-item.active {
  color: #89CFF0;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  width: 60rpx;
  height: 6rpx;
  background-color: #89CFF0;
  border-radius: 3rpx;
}

.tab-text {
  font-size: 28rpx;
}

.tab-count {
  font-size: 20rpx;
  color: #999;
  background-color: #f0f0f0;
  border-radius: 10rpx;
  padding: 2rpx 8rpx;
  margin-left: 10rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 300rpx;
}

.empty-img {
  width: 200rpx;
  margin-bottom: 40rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
}

.requests-list {
  padding: 20rpx;
}

.request-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.user-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-right: 24rpx;
  background-color: #eee;
}

.request-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.user-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.request-time {
  font-size: 24rpx;
  color: #999;
}

.request-message {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 16rpx;
}

.status-tag {
  align-self: flex-start;
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
}

.status-tag.pending {
  background-color: #FFF3E0;
  color: #FF9800;
}

.status-tag.accepted {
  background-color: #E8F5E9;
  color: #4CAF50;
}

.status-tag.rejected {
  background-color: #FFEBEE;
  color: #F44336;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.action-btn {
  padding: 10rpx 20rpx;
  font-size: 24rpx;
  border-radius: 10rpx;
  min-width: 100rpx;
  text-align: center;
}

.accept-btn {
  background-color: #89CFF0;
  color: white;
}

.reject-btn {
  background-color: #FF3B30;
  color: white;
}
</style>